import { memo, useCallback, useEffect, useMemo, useState } from 'react'
// import { useNavigate } from 'react-router-dom'
// import { message } from 'antd'
import { useRecoilState, useSetRecoilState } from 'recoil'
// import { userState, CurrentUser } from '@/store/user'

import PageLoading from '@/components/PageLoading'

// import { ResponseData } from '@/utils/request'
// import { queryCurrent } from '@/services/user'
// import { isNullData } from '@/utils'
import { userInfo } from '@/store/userInfo'
import { GETUSERINFO, dict, getInfo } from '@/pages/user/login/service/service'
import { dictValues } from '@/store/dicts'
import { getToken } from '@/utils/localToken'
import { platformDetailsInfo } from '@/store/platformDetails'

export interface SecurityLayoutProps {
  children: React.ReactNode
}

export default memo(({ children }: SecurityLayoutProps) => {
  // 存所有的字典
  const setDictValues = useSetRecoilState(dictValues)
  // 存储用户信息
  const setTopUserInfo = useSetRecoilState(userInfo)
  // 存储平台信息
  const setPlatformInfo = useSetRecoilState(platformDetailsInfo)
  // const navigate = useNavigate()

  const [loading, setLoading] = useState<boolean>(false)

  // 存放顶部管理员所有信息
  const getUserInfo = async () => {
    const responseUserInfo = await GETUSERINFO()
    console.log('responseUserInfo🚀🚀🚀🚀', responseUserInfo)
    setTopUserInfo(responseUserInfo.data)
  }

  // 获取字典的管理员数组
  const dictGet = async () => {
    const res = await dict()

    // 存 recoil 所有的字典
    const filat = res.data?.reduce((acc: any, item: any) => {
      const key = Object.keys(item)[0]
      const value = item[key]
      acc[key] = value
      return acc
    }, {})
    setDictValues(filat)
  }

  // 获取平台信息
  const getPlatformInfo = async () => {
    // const res = await getInfo({ website: window.location.origin })

    const res = await getInfo({ website: 'http://192.168.120.148:8012' })
    setPlatformInfo(res.data)
  }

  const init = async () => {
    setLoading(true)
    // 拦截没有token进入路由
    if (!getToken()) {
      window.location.href = '/user/login'
      return
    }
    await getUserInfo()
    await dictGet()
    await getPlatformInfo()
    setLoading(false)
  }

  // 相当于点击登录的时候做了一个中转，登录进入一进来就去请求用户详细接口，PageLoading是加载效果
  useEffect(() => {
    init()
  }, [])

  return <>{loading ? <PageLoading /> : children}</>
})
